<?php
include_once('./config/config.php');
$admin = AuthCheck();
$action = $_GET['action'] ?? '';
// 退出账号
if ($action === 'logout') {
  setcookie('auth', '', time() - 1);
  notice('退出成功', 'login.php');
}
// 获取地址栏的id
$id = isset($_GET['id']) ? trim($_GET['id']) : 0;
// 检查id
$sql = "SELECT  * FROM `pre_admin` WHERE `id` = '$id'";
$person = find($sql);
if (!$person) {
  notice('管理员不存在', 'AdminList.php');
  exit;
}
// 不允许操作别的管理员
$checkId = json_decode($_COOKIE['auth'], true)['id'];
if ($id != $checkId) {
  notice('非法操作', 'AdminList.php');
  exit;
}

// 判断是否有表单提交
if ($_POST) {
  // 接收参数
  $username = isset($_POST['username']) ? trim($_POST['username']) : '';
  $password = isset($_POST['password']) ? trim($_POST['password']) : '';

  // 判断参数是否为空
  if (empty($username)) {
    notice('用户名不能为空');
  }

  // 组装数据
  $data = [
    'username' => $username,
  ];
  // 如果修改密码
  if (!empty($password)) {
    // 生成密码盐
    $salt = build_randstr();
    // 拼接加密
    $password = md5($password . $salt);
    $data['salt'] = $salt;
    $data['password'] = $password;
  }

  // 上传头像
  if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
    $avatar = build_upload('avatar');
    if ($avatar['code'] === 0) {
      notice($avatar['msg']);
    }
    $data['avatar'] = $avatar['data'];
  }
  $result = update('admin', $data, "`id` = $id");

  if ($result === true) {
    // 更新成功就把旧头像删除
    if (isset($data['avatar']) && $_FILES['avatar']['size'] > 0) {
      @is_file('.' . $person['avatar']) && unlink('.' . $person['avatar']);
    }
    setcookie('auth', '', time() - 1);
    notice('修改账号信息成功,请重新登录', 'login.php');
  } else {
    // 更新失败就把新的头像删除
    if (isset($data['avatar']) && $_FILES['avatar']['size'] > 0) {
      @is_file('.' . $data['avatar']) && unlink('.' . $data['avatar']);
    }
    echo $result;
    exit;
  }
}

?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>admin</title>
  <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="author" content="">

  <!-- 公共样式 -->
  <?php include_once('./common/meta.php'); ?>
  <style>
    #upload {
      width: 214px;
      height: 200px;
      object-fit: cover;
      cursor: pointer;
    }
  </style>

  <!-- jquery -->
  <script src="./assets/lib/jquery-1.7.2.min.js" type="text/javascript"></script>

</head>

<body>
  <!-- 引入头部 -->
  <?php include_once('common/header.php'); ?>

  <!-- 侧边菜单栏 -->
  <?php include_once('common/menu.php'); ?>

  <div class="content">
    <div class="header">
      <h1 class="page-title">编辑管理员</h1>
    </div>
    <ul class="breadcrumb">
      <li><a href="AdminList.php">AdminList</a> <span class="divider">/</span></li>
      <li class="active">AdminEdit</li>
    </ul>

    <div class="container-fluid">
      <div class="row-fluid">
        <div class="btn-toolbar">
          <button class="btn btn-primary" onClick="location='AdminList.php'"><i class="icon-list"></i> 管理员列表</button>
          <div class="btn-group"></div>
        </div>

        <div class="well">
          <div id="myTabContent" class="tab-content">
            <div class="tab-pane active in" id="home">
              <form method="post" enctype="multipart/form-data">
                <!-- 用户名 -->
                <label>用户名</label>
                <input type="text" name="username" value="<?php echo $person['username'] ?>" id="username" placeholder="请输入用户名" class="input-xxlarge">
                <span id="username-error"></span>

                <label>密码</label>
                <input type="password" name="password" placeholder="不修改密码请留空" class="input-xxlarge">

                <label>头像</label>
                <input type="file" name="avatar" id="avatar" hidden class="input-xxlarge">
                <img src="<?php echo is_file('.' . $person['avatar']) ? $person['avatar'] : './assets/images/upload.png' ?>" id="upload" alt="">

                <label></label>
                <input class="btn btn-primary" type="submit" value="提交" />
              </form>
            </div>
          </div>
        </div>

        <!-- 引入底部 -->
        <?php include_once('common/footer.php'); ?>
      </div>
    </div>
  </div>
</body>

</html>

<?php include_once('common/script.php'); ?>

<script>
  $('#upload').click(function() {
    $('#avatar').click();
  })

  $('#avatar').change(function() {
    let file = this.files[0] ?? '';

    if (file) {
      let Reader = new FileReader();

      Reader.readAsDataURL(file);

      Reader.onload = function() {
        $('#upload').attr('src', Reader.result);
      }
    }
  })

  $('#username').change(function() {
    let username = $.trim($(this).val());

    if (!username) {
      return false;
    }

    // 发起请求
    $.ajax({
      type: 'post',
      url: 'api.php',
      data: {
        username,
        action: 'select_admin_username'
      },
      dataType: 'json',
      success: (result) => {
        if (result.code === 1) {
          $('#username-error').text(result.msg).css({
            color: 'green',
            fontSize: '16px'
          })
        } else {
          $('#username-error').text(result.msg).css({
            color: 'red',
            fontSize: '16px'
          })
        }
      }
    })
  })
</script>